package com.huikeportal.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.huikeportal.controller.common.Lang;
import com.huikeportal.model.ChangeGcParam;
import com.huikeportal.model.Language;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteSelectParam;
import com.huikeportal.model.SiteSimpleInfo;
import com.huikeportal.model.SquareChange;
import com.huikeportal.model.TodayIndexes;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.CommonService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.SquareWeekService;
import com.huikeportal.service.TodayIndexesService;

/**
 * 
 * @author wenyp
 *	星期对比
 */

@Controller
public class SquareWeekController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;

	@Autowired
	private FootfallGlobalService footfallGlobalService;
	
	@Autowired
	private SquareWeekService squareWeekService;
	
	@Autowired
	private TodayIndexesService todayIndexesService;
	
	@Autowired
	SelectSiteService selectSiteService;
	
	@Autowired
	private CommonService commonService;

	/**初始化全局分析页面  */
	@RequestMapping("/squareWeek")
	public String squareWeek(RedirectAttributes attr, ModelMap model,String siteId,HttpServletRequest request,HttpServletResponse response) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String userId=userInfo.getUserId();
//		if(siteId==null||"".equals(siteId)){
//			SiteSelectParam siteSelectParam=new SiteSelectParam();
//			siteSelectParam.setPageFrom("squareWeek");
//			siteSelectParam.setControlTo("squareWeek");
//			siteSelectParam.setChoiceType("1");
//			siteSelectParam.setRangeType("1");
//			request.setAttribute("siteSelectParam", siteSelectParam);
//			return "forward:/mulChoiceLoad";
//		}
		//获取当前系统语言
        String sysLang = session.getAttribute("sysLang").toString();
        //查询当前页面id
        SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString("squareWeek");
        Integer menuId = selectSiteService.getMenuId(sql);
        //获取用户权限按钮信息
        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
                userId, menuId);
        
        String buttonExport = "0";
        for(WordBook wordBook:buttonList){
        	if("导出".equals(wordBook.getDicValue())){
        		buttonExport = "1";
        		break;
        	}
        }
        
        /** 选择场所初始化 **/
		// 更换广场div初始化数据
		List<SiteAllInfo> dpGcList = loginService.getDpGcSiteList(userInfo);
		ChangeGcParam changeGcParam = new ChangeGcParam();
		changeGcParam.setSelectType("0");// 单选场所
		List<SiteAllInfo> yuanGcList = loginService.getGcSiteList(userInfo);
		SquareChange squareChange = selectSiteService.squareChangeLoad(
				changeGcParam, dpGcList,yuanGcList);// 获取初始化更换广场信息
		model.addAttribute("squareChange", squareChange);// 更换广场数据初始化
		model.addAttribute("selectType", changeGcParam.getSelectType());// 选择类型，1为多选
		model.addAttribute("pageType", "1");// 页面类型，带集团，0表示不带集团
		model.addAttribute("backPage", "squareWeek");// 返回地址
		// 初始化查询集团&地区列表
		SqlParameter sqlParam = new SqlParameter();
		sqlParam.setString(userInfo.getUserId());
		List<SiteAllInfo> jtDqList = selectSiteService.getJtDqList(sqlParam);
		model.addAttribute("jtDqList", jtDqList);
		if (siteId != null && !"".equals(siteId)) {
			// 根据场所id查询场所信息
			List<SiteSimpleInfo> selectedSiteList = selectSiteService
					.getSimpleSiteList(siteId);
			// 将已选择的场所传回到页面上
			model.addAttribute("selectedSiteList", JSONArray.fromObject(
					selectedSiteList).toString());
		} 
		
		String siteType=FootfallConstant.WHOLE_SITETYPE;//场所类型是300
		SiteAllInfo siteAllInfo=footfallGlobalService.selectSiteByUserId(userInfo,siteType);
		String siteID="";
		if(siteId!=null&& !siteId.equals("")){
			siteID=siteId;
		}else{
			model.addAttribute("datetime", footfallGlobalService.getDate());
			Language lang = Lang.getInfo(sysLang);
			model.addAttribute("lang",lang);
			String menuHtml = loginService.getMenuHtml(userInfo, "squareWeek");//设置左侧列表菜单
			model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
			return "squareWeek";
		}

	
		siteId = siteID;
		
        /**初始化指标权限*/
        List<String> siteTypes = footfallGlobalService.getSiteTypes(siteId);
        /**获取用户指标权限*/
        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
        //数据分析-星期分析model为'2_3'
        String moduleId = FootfallConstant.WEEKCOMP;
        //获取趋势分析指标
        List<String> indexList = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId, siteTypes);
        //取趋势分析指标分组
        HashMap<String, List<String>> indexListOfGroup = footfallGlobalService.getIndexListOfGroup(indexList);
        model.addAttribute("indexList",JSONObject.fromObject(indexListOfGroup));
        
      //获取排行榜各时间指标
        HashMap<String, Object> dateIndexMap = new HashMap<String, Object>();
        List<String> indexHour  = footfallGlobalService.getTimeIndex("hour");
        dateIndexMap.put("indexHour", indexHour);
        List<String> indexDay  = footfallGlobalService.getTimeIndex("day");
        dateIndexMap.put("indexDay", indexDay);
        List<String> indexWeek  = footfallGlobalService.getTimeIndex("week");
        dateIndexMap.put("indexWeek", indexWeek);
        List<String> indexMonth  = footfallGlobalService.getTimeIndex("month");
        dateIndexMap.put("indexMonth", indexMonth);
        List<String> indexYear  = footfallGlobalService.getTimeIndex("year");
        dateIndexMap.put("indexYear", indexYear);
        model.addAttribute("dateIndexMap",JSONObject.fromObject(dateIndexMap));

        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
        model.addAttribute("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
        model.addAttribute("indexInfo",JSONObject.fromObject(indexInfo));
        /**初始化全局分析的指标权限结束*/
        
		if(siteID!=null&& !siteID.equals("")){
			String siteNames=footfallGlobalService.getSiteNames(siteID);
			String siteName=todayIndexesService.getSiteNameBySiteId(siteID);
			model.addAttribute("siteName", siteNames);
			model.addAttribute("siteId", siteID);
			model.addAttribute("datetime", footfallGlobalService.getDate());
		}
		model.addAttribute("buttonExport",buttonExport);
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang",lang);
		String menuHtml = loginService.getMenuHtml(userInfo, "squareWeek");//设置左侧列表菜单
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		return "squareWeek";
	}
	
	/**前台获取图表数据  */
	@SuppressWarnings("unchecked")
	@RequestMapping("/squareWeekGraph")
	@ResponseBody
	public HashMap<String , Object> squareWeekGraph(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
//		StringBuffer name1=request.get
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		
		String timeType_table=Strings[0];
		
		String timeType=Strings[1];
		
//		图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
//		如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		
		String siteId=request.getParameter("siteId");//获取场所
		
		HashMap<String , Object> paraMapResult = new HashMap<String, Object>();
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("type", type);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		
		List<HashMap<String, Object>> Result =squareWeekService.getGraphData(paraMap);
		
		//最多显示7条数据，多余的从底部去掉
		while(Result.size()>7){
			Result.remove(0);	
		}
		String siteNames=footfallGlobalService.getSiteNames(siteId);//前台导航栏地址 广场-场所
		paraMapResult.put("siteN", siteNames);
		String sitename=footfallGlobalService.getSiteName(siteId);//siteId的中文名称
		paraMapResult.put("siteName", sitename);
		
		
		/** 获取siteId 的场所类型中文名称*/
		List<String> siteType = footfallGlobalService.getSiteTypes(siteId);
		String siteTypeName = "";
		if(siteType!=null&&!"".equals(siteType)){
			String siteType1 = siteType.get(0);
			siteTypeName = footfallGlobalService.getSiteTypeName(Integer.parseInt(siteType1));
		}
		paraMapResult.put("siteTypeName", siteTypeName);
		//根据日周月年的不同需要的参数map
//		HashMap<String, Object> pramMap1=footfallGlobalService.getparam(timeType_table,timeType,startDate,endDate);
		
		if("1".equals(timeType)){
			paraMapResult.put("stadubiao", commonService.getMondayOfWeek(0));
			paraMapResult.put("endtubiao", commonService.getSundayOfWeek(1));
		}else if("2".equals(timeType)){
			paraMapResult.put("stadubiao", commonService.getMondayOfWeek(-1) );
			paraMapResult.put("endtubiao",commonService.getSundayOfWeek(0));
		}else if("3".equals(timeType)){
			paraMapResult.put("stadubiao", commonService.getMondayOfWeek(-2) );
			paraMapResult.put("endtubiao",commonService.getSundayOfWeek(0));
		}else{
			List<ReportGraphData> stadubiaoresultList=(List<ReportGraphData>) Result.get(0).get("resultList");
			String stadubiao = stadubiaoresultList.get(0).getDatatime();
			List<ReportGraphData> endtubiaoresultList=(List<ReportGraphData>) Result.get(Result.size()-1).get("resultList");
			String endtubiao = endtubiaoresultList.get(endtubiaoresultList.size()-1).getDatatime();
			paraMapResult.put("stadubiao",stadubiao);
			paraMapResult.put("endtubiao",endtubiao);
		}
		//插入折线数据
		paraMapResult.put("result", Result);
		return paraMapResult;
	}
	


}
